package com.wutong.eams.controller;

import com.wutong.eams.dto.UserManagerDTO;
import com.wutong.eams.entity.User;
import com.wutong.eams.enums.Role;
import com.wutong.eams.enums.Status;
import com.wutong.eams.utils.StringUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@WebServlet("/api/users/*")
public class UserManagerController extends BaseController {

    @Override
    public Role getPermission() {
        return Role.TEACHER;
    }

    @Override
    public boolean needPermission() {
        return true;
    }

    /**
     * /api/users 创建用户，仅限管理员权限
     * @param req   请求对象
     * @param resp  响应对象
     * @throws ServletException 异常
     * @throws IOException 异常
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);

        if (!hasCurrentRule("/api/users", req, resp)) {
            // 路由不匹配
            log.warn("请求路径不匹配: {}", req.getRequestURI());
            resp.sendError(403, "Forbidden");
            return;
        }

        // JWT TOKEN 验证在Filter中完成
        User sessionUser = (User) req.getSession().getAttribute("user");
        if (sessionUser == null) {
            // 未登录
            log.warn("未登录: {}", req.getRequestURI());
            resp.sendError(401, "Unauthorized");
            // 重定向到登录页面
            routerRedirect("/page/login", req, resp);
            return;
        }
        if (!getUserAuthenticService().isMatchRole(sessionUser.getUsername(), Role.ADMIN)) {
            // 权限错误
            log.warn("权限不足: {}", sessionUser.getRole());
            resp.sendError(403, "Forbidden");
            return;
        }

        // 处理创建逻辑
        User user = new User(
                null,
                req.getParameter("username"),
                req.getParameter("password"),
                req.getParameter("realName"),
                req.getParameter("gender"),
                req.getParameter("role"),
                req.getParameter("email"),
                req.getParameter("phone"),
                Status.NORMAL.getValue(),
                new Date(),
                new Date()
        );
        UserManagerDTO.CreateUser createUserDTO = new UserManagerDTO.CreateUser(user);
        if (getUserManagerService().createUser(createUserDTO)) {
            // 成功
            resp.setStatus(200);
        } else {
            // 失败
            resp.sendError(500, "Internal Server Error");
        }
    }

    /**
     * GET    /api/users?page=?&size=? - 分页查询用户列表
     * GET    /api/users?id=?          - 获取用户详情
     * @param req   请求对象
     * @param resp  响应对象
     * @throws ServletException 异常
     * @throws IOException 异常
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);

        // JWT TOKEN 验证在Filter中完成
        // 处理分页查询：路由没有/{id}字样，有指定参数
        String pageStr = req.getParameter("page");
        String sizeStr = req.getParameter("size");
        String idStr = req.getParameter("id");
        if (!(pageStr == null || sizeStr == null)) {
            int page = Integer.parseInt(pageStr);
            int size = Integer.parseInt(sizeStr);
            List<User> users = getUserManagerService().queryUserByPage(new UserManagerDTO.QueryUserByPage(page, size));
            if (users == null) {
                // 查询失败
                log.warn("查询分页失败: {}", req.getRequestURI());
                resp.sendError(500, "Internal Server Error");
                return;
            }
            // 成功
            resp.setStatus(200);
            req.setAttribute("users", users);
        } else if (idStr != null) {
             // 处理获取用户详情
            User user = getUserManagerService().getUserById(new UserManagerDTO.GetUserById(Integer.parseInt(idStr)));
            if (user == null) {
                // 查询失败
                log.warn("查询用户详情失败: {}", req.getRequestURI());
                resp.sendError(500, "Internal Server Error");
                return;
            }
            req.setAttribute("user", user);
            // 成功
            resp.setStatus(200);
        } else {
            // 路由不匹配
            log.warn("请求GET路径不匹配: {}", req.getRequestURI());
            resp.sendError(404, "Not Found");
        }
    }

    /**
     * DELETE /api/users?id=? - 删除用户
     * @param req  请求对象
     * @param resp  响应对象
     * @throws ServletException 异常
     * @throws IOException 异常
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);
        // JWT TOKEN 验证在Filter中完成
        // 处理删除逻辑：路由没有/{id}字样，有指定参数
        String idStr = req.getParameter("id");
        if (idStr == null) {
            // 路由不匹配
            log.warn("请求DELETE路径不匹配: {}", req.getRequestURI());
            resp.sendError(404, "Not Found");
            return;
        }
        // 处理删除逻辑
        UserManagerDTO.DeleteUser deleteUserDTO = new UserManagerDTO.DeleteUser(Integer.parseInt(idStr));
        if (getUserManagerService().deleteUser(deleteUserDTO)) {
            // 成功
            resp.setStatus(200);
        } else {
            // 失败
            resp.sendError(500, "Internal Server Error");
        }
    }

    /**
     * POST   /api/users             - 更新用户
     * @param req  请求对象
     * @param resp  响应对象
     * @throws ServletException 异常
     * @throws IOException 异常
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        // JWT TOKEN 验证在Filter中完成
        // 从提交表单中获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realName = req.getParameter("realName");
        String gender = req.getParameter("gender");
        String role = req.getParameter("role");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        // 处理创建逻辑
        User user = new User(
                null,
                username,
                StringUtil.encrypt(password),
                realName,
                gender,
                role,
                email,
                phone,
                Status.NORMAL.getValue(),
                new Date(),
                new Date()
        );
        UserManagerDTO.UpdateUser updateUserDTO = new UserManagerDTO.UpdateUser(user);
        if (getUserManagerService().updateUser(updateUserDTO)) {
            // 成功
            resp.setStatus(200);
        } else {
            // 失败
            resp.sendError(500, "Internal Server Error");
        }
    }
}
